package kr.co.iniline.rumkb.server;

import java.util.ArrayList;
import java.util.Vector;

public class UserManager {
	Vector<User> userList = null;
	User master = null;
	
	int turnCount = 0;
	boolean hasTurn = false;
	User turnedUser = null;
	
	public UserManager(String userID) {
		this.master = new User(userID);
		userList = new Vector<User>();
		joinUser( userID ).isCreator = true;
	}
	
	public boolean hasTurn() {
		return hasTurn;
	}
	
	public User nextTurn() {
		User user = turnedUser = getUsers()[ turnCount ];
		if( ++turnCount >= getUserNum() ) {
			turnCount = 0;
		}
		hasTurn = true;
		return user;
	}
	
	public User currentTurnUser() {
		return turnedUser;
	}
	
	public User[] getUsers() {
		return userList.toArray( new User[userList.size()] );
	}
	
	User addUser(String userID) {
		if( userList.size() >= 4 ) {
			return null;
		}
		User user = new User(userID);
		userList.add( user );
		return user;
	}
	
	public int getUserNum() {
		return userList.size();
	}
	
	public User joinUser(String userID) {
		User user = addUser(userID);
		if( user != null ) {
			informUserListEvent();
		}
		return user;
	}
	
	public User getUser(String userID) {
		for (int i = 0; i < userList.size(); i++) {
			User user = userList.get(i);
			if(user.userID.equals(userID)) {
				return user;
			}
		}
		return null;
	}
	
	public boolean quitUser(String userID) {
		for (int i = 0; i < userList.size(); i++) {
			User user = userList.get(i);
			if(user.userID.equals(userID)) {
				return userList.remove( user );
			}
		}
		return false;
	}
	
	public User getMaster() {
		return master;
	}
	
	public void informEvent(RmkbEvent event) {
		for (int i = 0; i < userList.size(); i++) {
			User user = userList.get(i);
			user.informEvent( event );
		}
	}
	
	public void informEventWithoutOne(User user, RmkbEvent event) {
		informEventWithoutOne(user.userID, event);
	}
	
	public void informEventWithoutOne(String id, RmkbEvent event) {
		for (int i = 0; i < userList.size(); i++) {
			User user = userList.get(i);
			if( !user.userID.equals(id) ) {
				user.informEvent( event );
			}
		}
	}
	
	public void informUserListEvent() {
		ArrayList<String> list = new ArrayList<String>();
		for (int i = 0; i < userList.size(); i++) {
			User user = userList.get(i);
			list.add( user.userID );
		}
		RmkbEvent event = RmkbEvent.UserList.userList( list.toArray(new String[list.size()]) );
		informEvent( event );
	}
	
	public void resetState() {
		turnCount = 0;
		hasTurn = false;
		turnedUser = null;
		User users[] = getUsers();
		for (int i = 0; i < users.length; i++) {
			users[i].reset();
		}
	}
}
